package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.KafkaConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.kafka.MessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author 熏橙橙
 * @version 1.0
 * @date 2023-08-04 10:58
 */
@Component
@Slf4j
public class ArticlesCountListener {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApArticleService apArticleService;
    /**
     * 数量统计
     *
     * @return
     */
    @KafkaListener(topics = KafkaConstants.MSG)
    //@Scheduled(cron = "0 0 8 * * ?")
    public void cont(String msg) {

        MessageDto messageDto = JSON.parseObject(msg, MessageDto.class);
        String apArticleId = messageDto.getApArticleId();
        ApArticle apArticle = apArticleService.getById(apArticleId);
        Integer type = messageDto.getType();
        if (type==null){
            return;
        }
        if (type==1){
//            String likePattern = BehaviorConstants.LIKES + "*" +apArticleId;
//            Set<String> likeKeys = cacheService.scan(likePattern);
                apArticle.setLikes(apArticle.getLikes() + messageDto.getCount());
        }
        if (type==2){
                apArticle.setViews(apArticle.getViews() + messageDto.getCount());
        }
        if (type==3){
                apArticle.setCollection(apArticle.getCollection() + messageDto.getCount());
        }
       /* String readPattern = BehaviorConstants.READ + "*" + apArticleId;
        String collectionPattern = BehaviorConstants.COLLECTION + "*" + apArticleId;
        Set<String> readKeys = cacheService.scan(readPattern);
        Set<String> collectionKeys = cacheService.scan(collectionPattern);*/
//        apArticle.setViews(readKeys.size());
//        apArticle.setCollection(collectionKeys.size());
        apArticleService.updateById(apArticle);
    }
}
